package com.cn.lf.wx.dacs.bussiness.author.serviceImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.lf.wx.dacs.bussiness.author.dao.HisMapper;
import com.cn.ym.log.Log;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-03-01
 */
@Service("HisMapper")
public class HisServiceImpl {

	@Autowired
	private HisMapper hisMapper;
	
	private  String DEFAULT_URL = "http://218.75.49.10:8991/etzl/api/";

	// 获取data
	public String getData(Map<String, Object> map) {
		String url = "";
		if("1".equals(map.get("type"))){
			url = DEFAULT_URL + "getListByName";
		}else {
			url = DEFAULT_URL + "getDataBybah";
		}
		String json = JSONObject.toJSONString(map);
		List<Map<String,Object>> allList = toListMap(doPost(url,json));
		//详情入参
		Map<String,Object> maps = new HashMap<String, Object>();
		String urls = "";
		String jsons = "";
		// 此处为特判出院诊断内嵌数组
		if ("v_etzl_dischargeDiagnosisInfo".equals(map.get("viewName"))) {
			for (int i = 0; i < allList.size(); i++) {
				// 获取其它诊断
				urls = DEFAULT_URL + "getQtzd";
				maps.put("ncNumber", allList.get(i).get("ncMedicalRecordNo"));
				jsons = JSONObject.toJSONString(maps);
				allList.get(i).put("ncOtherDiagnosis", JSON.parse(doPost(urls,jsons)));
				// 其它俩暂时没数据
				String url2 = DEFAULT_URL + "getBlzd";
				allList.get(i).put("ncPathologyDiagnosis",JSON.parse(doPost(url2,jsons)));
				allList.get(i).put("ncTumourPosition", new ArrayList<Map<String, Object>>());
			}
		}
		if ("v_etzl_pathologyInfo".equals(map.get("viewName"))) {
			for (int i = 0; i < allList.size(); i++) {
				// 获取病理记录
				urls = DEFAULT_URL + "getBljl";
				maps.put("ncNumber", allList.get(i).get("ncPathologyNo"));
				jsons = JSONObject.toJSONString(maps);
				allList.get(i).put("ncSpecimen", JSON.parse(doPost(urls,jsons)));
			}
		}
		if ("v_etzl_deathRecord".equals(map.get("viewName"))) {
			for (int i = 0; i < allList.size(); i++) {
				// 死亡诊断
				List<Map<String,Object>> lists = new ArrayList<Map<String,Object>>();
				Map<String,Object> newmap = new HashMap<String, Object>();
				newmap.put("ncDeathReasonIcd10Code",allList.get(i).get("ncDeathReasonIcd10Code"));
				newmap.put("ncDeathReasonDiagnosisName",allList.get(i).get("ncDeathReasonDiagnosisName"));
				newmap.put("ncDeathReasonIcdCodeL",allList.get(i).get("ncDeathReasonIcdCodeL"));
				newmap.put("ncDeathReasonDiagnosisNameL",allList.get(i).get("ncDeathReasonDiagnosisNameL"));
				newmap.put("ncDeathReasonDiagnosisVerNameL",allList.get(i).get("ncDeathReasonDiagnosisVerNameL"));	
				lists.add(newmap);
				jsons = JSONObject.toJSONString(lists);
				allList.get(i).put("ncDeathDiagnosisList",JSON.parse(jsons));
			}
		}
		if("v_etzl_fistDiseaseCourse_xml".equals(map.get("viewName"))) {
			for (int i = 0; i < allList.size(); i++) {
				// 获取病程clob
				urls = DEFAULT_URL + "getbcclog";
				maps.put("ncNumber", allList.get(i).get("ncMedicalRecordNo"));
				jsons = JSONObject.toJSONString(maps);
				allList.get(i).remove("ncCaseCharacteristics");
				allList.get(i).put("ncCaseCharacteristics", doPost(urls,jsons));
			}
		}
		if("v_etzl_diseaseCourse_cf".equals(map.get("viewName"))) {
			for (int i = 0; i < allList.size(); i++) {
				// 获取病程clob
				urls = DEFAULT_URL + "getbcdetail";
				maps.put("ncNumber", allList.get(i).get("ncMedicalRecordNo"));
				maps.put("ncCode", allList.get(i).get("ncDiseaseCourseNo"));
				jsons = JSONObject.toJSONString(maps);
				allList.get(i).remove("ncCourseDetail");
				allList.get(i).put("ncCourseDetail", doPost(urls,jsons));
			}
		}
		Log.info("-->"+allList);
    	//拼接
		Map<String,Object> ed = new HashMap<String, Object>();	
		String str = JSON.toJSONString(allList);
		ed.put("dataList", JSON.parse(str));
		return JSON.toJSONString(ed);
	}

	public String selectByDate() {
		String url = DEFAULT_URL + "getDate";
		return doPost(url,"");
	}

public  String doPost(String url,String json){
	 try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
         HttpPost post = new HttpPost(url);
         post.setHeader("Content-Type", "application/json");
         StringEntity entity = new StringEntity(json);
         post.setEntity(entity);
         try (CloseableHttpResponse response = httpClient.execute(post)) {
             HttpEntity responseEntity = response.getEntity();
             if (responseEntity != null) {
                 String result = EntityUtils.toString(responseEntity);
                 Log.info(result);
                 return result;
             }
             return "";
         }
     } catch (Exception e) {
         e.printStackTrace();
         return e.getMessage();
     }
}
public  List<Map<String, Object>> toListMap(String json){
    List<Object> list =JSON.parseArray(json);
    List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
    for (Object object : list){
        Map<String,Object> ageMap = new HashMap<String,Object>();
        Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
        listw.add(ret);
    }
    return listw;
     
}

//获取etzl_scbrxx所有数据
public List<Map<String, Object>> getAll(){
	String url = DEFAULT_URL + "getAll";
	return toListMap(doPost(url,""));
}

public String test(){
	String url = DEFAULT_URL + "test";
	return doPost(url,"");
}

public void insertSelectiveLog(Map<String,Object> map) {
	String url = DEFAULT_URL + "insertSelectiveLog";
	doPost(url,JSON.toJSONString(map));
}

//public void viewFile(HttpServletResponse response, String fileId) throws IOException {
//    Log.info("fileId == > " + fileId);
//
//    String filePath = "D:\\upload\\";// 上传到这个文件夹
//    String fileTypeDb = fileId.split("\\.")[1];
//    String targetPath = filePath + File.separator + fileId;
//
//    Log.info("targetPath == >" + targetPath);
//    File file = new File(targetPath);
//    OutputStream writer = null;
//    FileInputStream ips = null;
//    try {
//        ips = new FileInputStream(file);
////            返回类型
////        response.setCharacterEncoding("GBK");
////        response.setHeader("content-type","text/html;charset=utf-8");
//        response.setContentType(getConentType(fileTypeDb));
//        writer = response.getOutputStream();
//        // 读取文件流
//        int len;
//        byte[] buffer = new byte[1024];
//        while ((len = ips.read(buffer)) != -1) {
//            writer.write(buffer, 0, len);
//        }
//        writer.flush();
//    } catch (Exception e) {
////        不能抛出 返回空就可以
//        Log.error("file search : " + e.getMessage());
//    } finally {
//        if (Objects.nonNull(ips)) {
//            ips.close();
//        }
//        if (Objects.nonNull(writer)) {
//            writer.close();
//        }
//    }
//
//}
//
//private String getConentType(String fileTypeDb) {
//    if ("png".equals(fileTypeDb))
//        return "image/png";
//    else if ("jpg".equals(fileTypeDb))
//        return "image/jpeg";
//    else if ("pdf".equals(fileTypeDb))
//        return "application/pdf";
//    else if ("docx".equals(fileTypeDb))
//        return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//    else if ("doc".equals(fileTypeDb))
//        return "application/msword";
//    else
//        return "image/png";
//}


}
